/*
 * modbus.c
 *
 *  Created on: May 29, 2024
 *      Author: 86136
 */
#include<stdio.h>
#include<string.h>
#include "modbus.h"
#include "stm32l4xx_hal.h"
#include "usart.h"

uint8_t rx_buff[32];

uint16_t Modbus_CRC(uint8_t *buffer, uint16_t length)
{
    uint16_t crc = 0xFFFF;
    for (int i = 0; i < length; i++)
    {
        crc ^= buffer[i];
        for (int j = 0; j < 8; j++)
        {
            if (crc & 1)
                crc = (crc >> 1) ^ 0xA001;
            else
                crc >>= 1;
        }
    }
    return crc;
}

void Modbus_master_send(uint16_t Reg_start_addr, uint16_t num)
{
	uint8_t tx_buff[8];
	uint8_t modbus_function = 0x03;
	uint16_t crc;

	tx_buff[0] = Slave_addr;
	tx_buff[1] = modbus_function;
	tx_buff[2] = (Reg_start_addr >> 8) & 0xFF;
	tx_buff[3] = Reg_start_addr & 0xFF;
	tx_buff[4] = (num >> 8) & 0xFF;
	tx_buff[5] = num & 0xFF;
	crc = Modbus_CRC(tx_buff,6);
	tx_buff[6] = (crc >> 8) & 0xFF;
	tx_buff[7] = crc & 0xFF;

	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, GPIO_PIN_SET);
	HAL_UART_Transmit(&hlpuart1, tx_buff, 8, 0xFFFF);

	HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, GPIO_PIN_RESET);
	HAL_UART_Receive(&hlpuart1, rx_buff, 16, 0xFFFF);
	//printf("%s\r\n",rx_buff);
}
